/*////////////////////////////////////////////////////////////////////////
*
*  Project:      mapgenUI
*  Description:  UI created in Qt for Map Generator.
*  Author:       Copyright (C) 2010 Alexander Makodzeba
*  License:      GPLv3
*
*  This file is part of mapgen.
*
*  mapgen is free software: you can redistribute it and/or modify
*  it under the terms of the GNU General Public License as published by
*  the Free Software Foundation, either version 3 of the License, or
*  (at your option) any later version.
*
*  mapgen is distributed in the hope that it will be useful,
*  but WITHOUT ANY WARRANTY; without even the implied warranty of
*  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
*  GNU General Public License for more details.
*
*  You should have received a copy of the GNU General Public License
*  along with mapgen.  If not, see <http://www.gnu.org/licenses/>.
*
////////////////////////////////////////////////////////////////////////*/

#include "maindialog.h"
#include "ui_maindialog.h"
#include <QFileDialog>
#include <QDir>

//////////////////////////////////////////////////////////////////////////
// constructor
MainDialog::MainDialog(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::MainDialog)
{
    ui->setupUi(this);
    ui->edtLogs->hide();
    ui->dlgLayout->setSizeConstraint(QLayout::SetFixedSize);

    // subscribing on thread events
    connect(&process, SIGNAL(readyReadStandardOutput()),
            this, SLOT(processStandardOutputReady()));
    connect(&process, SIGNAL(finished(int, QProcess::ExitStatus)),
            this, SLOT(processFinished(int, QProcess::ExitStatus)));
    connect(&process, SIGNAL(error(QProcess::ProcessError)),
            this, SLOT(processError(QProcess::ProcessError)));

}

//////////////////////////////////////////////////////////////////////////
// destructor
MainDialog::~MainDialog()
{
    delete ui;
}

//////////////////////////////////////////////////////////////////////////
// button "..." click
void MainDialog::on_btnMapGenPath_clicked()
{
    ShowBrowsePath();
}

//////////////////////////////////////////////////////////////////////////
// button "Generate" click
void MainDialog::on_btnGenerate_clicked()
{
    StartProcess();
}

//////////////////////////////////////////////////////////////////////////
// signal: something in standard output
void MainDialog::processStandardOutputReady()
{
    QByteArray newData = process.readAllStandardOutput();
    QString text = QString::fromLocal8Bit(newData);
    AddLog(text);
}

//////////////////////////////////////////////////////////////////////////
// signal: process finished
void MainDialog::processFinished(int exitCode, QProcess::ExitStatus exitStatus)
{
    QString sMessage = QString("<processFinished> exitCode: %1, exitStatus: %2")
            .arg(exitCode)
            .arg(exitStatus);
    AddLog(sMessage);
}

//////////////////////////////////////////////////////////////////////////
// signal: there was error on process
void MainDialog::processError(QProcess::ProcessError error)
{
    QString sErr;
    sErr.setNum(error);
    AddLog("<processError> error: " + sErr);

    if(error == QProcess::FailedToStart)
    {
        AddLog("<processError> The process failed to start. Either the invoked program is missing, or you may have insufficient permissions to invoke the program.");
        AddLog("<processError> Process name: '" + ui->edtMapGenPath->text() + "'");
    }
}

//////////////////////////////////////////////////////////////////////////
// write log to the logs window
void MainDialog::AddLog(QString sLog)
{
    if(!sLog.isEmpty())
        ui->edtLogs->appendPlainText(sLog);
}

//////////////////////////////////////////////////////////////////////////
// start mapgen with all the parameters
void MainDialog::StartProcess()
{
    //push parameters
    QStringList args;
    args << ui->edtMapPrefix->text();
    args << ui->spnMapsCount->text();
    args << QString("%1").arg(ui->chkSymmetric->isChecked());
    args << ui->spnPlayersCount->text();
    args << ui->spnPlayerPlanetSize->text();
    args << ui->spnPlayerPopulation->text();
    args << ui->spnSizeMin->text() + "-" + ui->spnSizeMax->text();
    args << ui->spnPopulationMin->text() + "-" + ui->spnPopulationMax->text();
    args << ui->spnPlanetsMin->text() + "-" + ui->spnPlanetsMax->text();
    args << ui->spnWorldLeft->text() + ":" + ui->spnWorldTop->text();
    args << ui->spnWorldRight->text() + ":" + ui->spnWorldBottom->text();

    //start process
    QString path = ui->edtMapGenPath->text();
    process.start(path, args);
}

//////////////////////////////////////////////////////////////////////////
// browse path to mapgen
void MainDialog::ShowBrowsePath()
{
    QString initialName = ui->edtMapGenPath->text();
    if(initialName.isEmpty())
    {
        initialName = QDir::homePath();
    }
    QString fileName = QFileDialog::getOpenFileName(
            this, tr("Choose File"), initialName);
    fileName = QDir::toNativeSeparators(fileName);
    if(!fileName.isEmpty())
    {
        ui->edtMapGenPath->setText(fileName);
    }
}
